package agent

import (
	"dub/app/web/managent/mandefine"
	"dub/define"
	"dub/define/grpcmodel"
	"dub/secrec"
	"dub/utils"
	"fmt"
	"io"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"
)

type AgentMemController struct {
	AgentBaseController
}

func (a *AgentMemController) Get() {
	a.TplName = "agent/mem/list.html"
}

func (a *AgentMemController) ToAdd() {
	a.TplName = "agent/mem/add.html"
}

func (a *AgentMemController) MemDetailed() {
	jsons := make(map[string]interface{})
	jsons["result"] = false
	jsons["msg"] = "服务错误"

	for {
		memId, _ := a.GetInt("memId", 0)
		if memId < 1 {
			jsons["msg"] = "参数不合法"
			break
		}

		args := &grpcmodel.ModelSecRpcMemReqFind{MemId: uint32(memId), IsFindShow: true}
		use_rpc := secrec.GetRpc(secrec.ConstServiceUseRpc)
		if use_rpc == nil {
			a.Log().Errorf("agent_mem_controller.go MemDetailed method not find use_rpc info GetRpc\n")
			break
		}
		sec_mem := grpcmodel.NewISecRpcMemClient(use_rpc.Conn())
		reply, err := sec_mem.FindMem(use_rpc.Context(), args)
		if err != nil {
			a.Log().Errorf("agent_mem_controller.go MemDetailed method s.dbRpc.Call SecMemRpc.FindMem err. %v\n", err)
			break
		}
		if reply.GetErr() > 0 {
			if reply.GetErr() > 2 {
				a.Log().Errorf("agent_mem_controller.go MemDetailed method s.dbRpc.Call SecMemRpc.FindMem params or sql connection err. \n")
			} else {
				a.Log().Errorf("agent_mem_controller.go MemDetailed method s.dbRpc.Call SecMemRpc.FindMem not find err. \n")
			}
			break
		}

		jsons["result"] = true
		jsons["memData"] = reply.GetModelSecRpcMem()
		break
	}

	a.Data["json"] = jsons
	a.ServeJSON()
}

func (a *AgentMemController) FindMems() {
	page, _ := a.GetUint32("page", 1)
	pageSize, _ := a.GetUint32("rows", 20)
	rows := make([]*grpcmodel.ModelSecRpcMem, 0)
	jsons := make(map[string]interface{})
	jsons["total"] = 0
	jsons["rows"] = rows

	for {
		//得到登录id
		int_man := a.GetSession(define.Web_Session_Name_Agent_Login_Use)
		man_val, man_ok := int_man.(grpcmodel.ModelSecRpcAgentResLogin)
		if !man_ok {
			jsons["msg"] = "登录不合法"
			break
		}

		args := &grpcmodel.ModelSecRpcMemReqFind{
			IsPage:   true,
			StartRow: (page - 1) * pageSize,
			PageSize: pageSize,
			AddUseId: man_val.GetModelSecRpcAgent().GetAgentId(),
		}
		use_rpc := secrec.GetRpc(secrec.ConstServiceUseRpc)
		if use_rpc == nil {
			a.Log().Errorf("agent_mem_controller.go FindMems method not find use_rpc info GetRpc\n")
			break
		}
		sec_mem := grpcmodel.NewISecRpcMemClient(use_rpc.Conn())
		reply, err := sec_mem.Find(use_rpc.Context(), args)
		if err != nil {
			a.Log().Errorf("agent_mem_controller.go FindMems method sec_mem.Find err. %v\n", err)
			break
		}
		if reply.GetErr() > 0 {
			break
		}
		rows = reply.GetRows()
		jsons["rows"] = rows
		jsons["total"] = reply.GetTotal()

		break
	}

	a.Data["json"] = jsons
	a.ServeJSON()
}

func (a *AgentMemController) AddMem() {
	//先认为添加失败
	a.TplName = "agent/mem/add.html"
	msg := "参数错误"
	for {
		memName := a.GetString("memName", "")
		if memName == "" {
			break
		}
		memPhone := a.GetString("memPhone", "")
		memPhone_vali, _ := regexp.MatchString("1[0-9]{10}", memPhone)
		if !memPhone_vali {
			break
		}
		memBirthDate := a.GetString("memBirthDate", "")
		var time_birth time.Time
		memBirthDate_vali, _ := regexp.MatchString("([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))", memBirthDate)
		if !memBirthDate_vali {
			break
		} else {
			time_birth, _ = utils.TimeStrtoTime(memBirthDate)
		}
		memWxCode := a.GetString("memWxCode", "")
		memWxCode_vali, _ := regexp.MatchString("[0-9|a-z|A-Z|_]{5,}", memWxCode)
		if !memWxCode_vali {
			break
		}
		memQqCode := a.GetString("memQqCode", "")
		memQqCode_vali, _ := regexp.MatchString("[1-9][0-9]{4,}", memQqCode)
		if !memQqCode_vali {
			break
		}
		memSex := a.GetString("memSex", "")
		memSex_vali, _ := regexp.MatchString("[男|女]", memSex)
		if !memSex_vali {
			break
		}
		memHeight, _ := a.GetUint32("memHeight", 0)
		if memHeight < 30 {
			break
		}
		memEducation := a.GetString("memEducation", "")
		memEducation_vali, _ := regexp.MatchString("[初中|高中|中专|大专|本科|硕士|博士]", memEducation)
		if !memEducation_vali {
			break
		}
		memJob := a.GetString("memJob", "")
		if memJob == "" {
			break
		}
		memIncome, _ := a.GetUint32("memIncome", 0)
		if memIncome < 1 {
			break
		}
		memLiveRegionCode := a.GetString("memLiveRegionCode3", "")
		memLiveRegionCode_vali, _ := regexp.MatchString("[0-9]{6}", memLiveRegionCode)
		if !memLiveRegionCode_vali {
			break
		}
		memCensusRegionCode := a.GetString("memCensusRegionCode3", "")
		memCensusRegionCode_vali, _ := regexp.MatchString("[0-9]{6}", memCensusRegionCode)
		if !memCensusRegionCode_vali {
			break
		}
		memHouse := a.GetString("memHouse", "")
		memHouse_vali, _ := regexp.MatchString("[有|无]", memHouse)
		if !memHouse_vali {
			break
		}
		memCar := a.GetString("memCar", "")
		memCar_vali, _ := regexp.MatchString("[有|无]", memCar)
		if !memCar_vali {
			break
		}
		memRequirement := a.GetString("memRequirement", "")
		memLabelIds := a.GetString("memLabelIds", "")
		memEvaluation := a.GetString("memEvaluation", "")

		//当前登录人信息
		msg = "非法登录"
		ses_val := a.GetSession(define.Web_Session_Name_Agent_Login_Use)
		if ses_val == nil && mandefine.Lobby_Login_Url != "" {
			break
		}
		login_info, login_ok := ses_val.(grpcmodel.ModelSecRpcAgentResLogin)
		if !login_ok {
			break
		}

		args := &grpcmodel.ModelSecRpcMemReqUpdate{
			ModelSecRpcMem: &grpcmodel.ModelSecRpcMem{
				MemName:             memName,
				MemPhone:            memPhone,
				MemWxCode:           memWxCode,
				MemQqCode:           memQqCode,
				MemSex:              memSex,
				MemEducation:        memEducation,
				MemLiveRegionCode:   memLiveRegionCode,
				MemCensusRegionCode: memCensusRegionCode,
				MemJob:              memJob,
				MemHouse:            memHouse,
				MemCar:              memCar,
				MemLabelIds:         memLabelIds,
				MemRequirement:      memRequirement,
				MemEvaluation:       memEvaluation,
				MemBirthDate:        uint64(time_birth.Unix()),
				MemHeight:           memHeight,
				MemIncome:           memIncome,
				MemStatus:           1,
				MemAddType:          1,
				MemAddUseId:         login_info.GetModelSecRpcAgent().GetAgentId(),
			},
		}
		use_rpc := secrec.GetRpc(secrec.ConstServiceUseRpc)
		if use_rpc == nil {
			a.Log().Errorf("agent_mem_controller.go AddMem method not find use_rpc info GetRpc\n")
			break
		}
		sec_mem := grpcmodel.NewISecRpcMemClient(use_rpc.Conn())
		reply, err := sec_mem.Add(use_rpc.Context(), args)
		if err != nil {
			a.Log().Errorf("agent_mem_controller.go AddMem method sec_mem.Add err. %v\n", err)
			break
		}
		// a.Log().Infof("SecMemRpc.AddMem reply is %+v\n", reply)
		if reply.GetErr() == 1 {
			msg = "有重复数据"
			break
		}

		a.Data["MemId"] = reply.GetMemId()
		msg = ""
		a.TplName = "agent/mem/uploadImg.html"
		break
	}

	if msg != "" {
		a.Data["msg"] = msg
	}
}

//上传图片
func (a *AgentMemController) UploadImg() {
	res := make(map[string]interface{})
	res["Success"] = false
	res["name"] = ""
	for {
		fileName := a.Ctx.Request.Header.Get("Dubuploadfilename")
		memId := a.Ctx.Request.Header.Get("DubuploadMemId")
		memId_vali, _ := regexp.MatchString(`^[1-9]\d*$`, memId)
		a.Log().Infof("upload %s to id is %s member.\n", fileName, memId)
		if fileName == "" || !memId_vali {
			break
		}
		newFileName := fmt.Sprintf("%s%s", utils.Guid(), fileName[strings.LastIndex(fileName, "."):])
		f, err := os.Create(mandefine.WebUploadDir + "/" + newFileName)
		if err != nil {
			a.Log().Infof("create file err. %+v\n", err)
			break
		}
		defer f.Close()
		w_count, err := io.Copy(f, a.Ctx.Request.Body)
		if err != nil {
			a.Log().Errorf("copy file err. %+v\n", err)
			break
		}

		//上传目录
		path := mandefine.WebUploadDir[strings.LastIndex(mandefine.WebUploadDir, "/"):]
		a.Log().Infof("write file count is %d\n", w_count)
		//上传的基本url
		//TODO:先写死是静态服务器的代理路径，之后通过服务器间通信的方式把url传过来
		static_url := fmt.Sprintf("/static%s/%s", path, newFileName)
		memId_val, _ := strconv.Atoi(memId)

		args := &grpcmodel.ModelSecRpcMemReqUpdate{
			UpdateType:     1,
			ModelSecRpcMem: &grpcmodel.ModelSecRpcMem{MemId: uint32(memId_val), MemShowPics: static_url},
		}
		use_rpc := secrec.GetRpc(secrec.ConstServiceUseRpc)
		if use_rpc == nil {
			a.Log().Errorf("agent_base_func_controller.go UploadImg method not find use_rpc info GetRpc\n")
			break
		}
		sec_mem := grpcmodel.NewISecRpcMemClient(use_rpc.Conn())
		reply, err := sec_mem.Update(use_rpc.Context(), args)
		if err != nil {
			a.Log().Errorf("agent_base_func_controller.go UploadImg method not find use_rpc info Call SecMemRpc.UpdateMem %v\n", err)
			break
		}
		a.Log().Errorf("uploadimg return reply info is %+v", reply)
		if reply.Err != 0 {
			break
		}

		res["Success"] = true
		res["name"] = fileName
		a.Data["json"] = res
		break
	}
	a.ServeJSON()
}
